import graphene
from flask import Flask
from flask_graphql import GraphQLView
import pymysql

def get_conn():
    db = pymysql.connect(host="localhost",port=3306,user='root',password='123',db='graphql',charset='utf8')
    cursor = db.cursor()
    return db,cursor

class Person(graphene.ObjectType):
    id = graphene.ID()
    name = graphene.String()

class Query(graphene.ObjectType):
    persons = graphene.List(Person)

    def resolve_persons(self,info):
        sql = 'select * from t_user'
        d,c = get_conn()
        c.execute(sql)
        rs = c.fetchall()
        users = []
        for r in rs:
            users.append(Person(id=r[0],name=r[1]))
        c.close()
        d.close()
        return users

if __name__ =='__main__':
    schema = graphene.Schema(query=Query)
    app = Flask(__name__)
    app.add_url_rule('/graphql',view_func=GraphQLView.as_view('grapql',schema=schema, graphiql=True))
    app.run(debug=True)